//
//  BIDCreateConstructionViewController.m
//  JuanChengOA
//
//  Created by mal on 2017/7/28.
//  Copyright © 2017年 mal. All rights reserved.
//

#import "BIDCreateConstructionViewController.h"

#import "BIDBrowserImageViewController.h"
#import "UIView+FindFirstResponder.h"
#import "ELCImagePickerHeader.h"
#import "BIDAddPhotoView.h"
#import "BIDUploadFile.h"
#import "BIDCustomTextView.h"

#import <MobileCoreServices/UTCoreTypes.h>
#import "BIDCreateActivityFooterView.h"
#import "BIDCreateMeetingCell.h"
#import "BIDWithSwitchMeetingCell.h"
#import "BIDCustomTextField.h"
#import "BIDCustomDateView.h"
#import "BIDMemberListViewController.h"

static NSString *addApplyURL = @"itemBuildingAndroid!addItemBuilding.action";

@interface BIDCreateConstructionViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, BIDCreateActivityFooterViewDelegate, ELCImagePickerControllerDelegate, UINavigationControllerDelegate, BIDUploadFileDelegate, UIScrollViewDelegate, BIDCustomDateViewDelegate, BIDMemberListViewControllerDelegate>
{
    NSMutableArray *_dataSourceArr;
    NSArray *_houseTypeArr;
    NSArray *_payTypeArr;
    NSArray *_rentTypeArr;
    //
    NSUInteger _maxImgCount;
    //
    BIDCreateActivityFooterView *_footerView;
    BIDUploadFile *_uploadFile;
    //获取焦点的编辑框的位置
    CGRect _desRect;
    BOOL _isRegister;
    //
    BIDCustomDateView *_dateView;
}
@end

@implementation BIDCreateConstructionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _maxImgCount = 3;
    // Do any additional setup after loading the view from its nib.
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.tableFooterView = [[UIView alloc] init];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(closeHandler)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(sendHandler)];
    //
    _dateView = [[BIDCustomDateView alloc] initWithMode:3];
    _dateView.delegate = self;
    _dateView.bIsInputView = YES;
    NSString *strRequestURL = @"";
    strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], addApplyURL];
    _uploadFile = [[BIDUploadFile alloc] initWithURL:strRequestURL];
    _uploadFile.delegate = self;
    //
    _footerView = [[[NSBundle mainBundle] loadNibNamed:@"BIDCreateActivityFooterView" owner:self options:nil] lastObject];
    _footerView.delegate = self;
    _footerView.contentTextView.placeholder = @"请填写内容";
    _footerView.contentTextView.inputAccessoryView = self.toolBar;
    _tableView.tableFooterView = _footerView;
    //
    [self prepareData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)prepareData
{
    _houseTypeArr = [[NSArray alloc] init];
    _payTypeArr = [[NSArray alloc] init];
    _rentTypeArr = [[NSArray alloc] init];
    NSArray *tempArr = nil;
    tempArr = @[@{@"title":@"接收人员", @"content":@"", @"value":@"", @"placeholder":@"请选择接收人员", @"keyboardType":@"person", @"menuArr":[NSNull null], @"field":@"receiveId"},
                @{@"title":@"标题", @"content":@"", @"value":@"", @"placeholder":@"请填写标题", @"keyboardType":@"normal", @"menuArr":[NSNull null], @"field":@"itemBuilding.title"}];
    _dataSourceArr = [[NSMutableArray alloc] initWithArray:tempArr];
}

- (void)closeHandler
{
    [self dismissViewControllerAnimated:YES completion:^{}];
}

/**
 提交
 */
- (void)sendHandler
{
    UIView *firstResponderView = [self.view findFirstResponder];
    if(firstResponderView)
    {
        NSUInteger tag = firstResponderView.tag;
        if([firstResponderView isKindOfClass:[UITextField class]])
        {
            UITextField *tf = (UITextField *)firstResponderView;
            NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:_dataSourceArr[tag]];
            NSString *str = tf.text;
            [dic setObject:str forKey:@"value"];
            [dic setObject:str forKey:@"content"];
            [_dataSourceArr replaceObjectAtIndex:tag withObject:dic];
        }
    }
    for(NSDictionary *dic in _dataSourceArr)
    {
        NSString *strContent = ANY2NSSTRING(dic[@"content"]);
        if(strContent.length == 0)
        {
            NSString *strMsg = [[NSString alloc] initWithFormat:@"%@不能为空", dic[@"title"]];
            [self showAlertView:strMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
            return;
        }
    }
    if(_footerView.contentTextView.text.length == 0)
    {
        [self showAlertView:@"请填写内容" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        return;
    }
    //
    if(_footerView.addPhotoView.imgArr.count>0)
    {
        [_uploadFile addData:@"userId" value:[AppDelegate getUserId]];
        for(NSDictionary *dic in _dataSourceArr)
        {
            [_uploadFile addData:dic[@"field"] value:dic[@"value"]];
        }
        int count = 0;
        for(UIImage *img in _footerView.addPhotoView.imgArr)
        {
            NSData *imgData = UIImageJPEGRepresentation(img, 0.5f);
            NSString *strFileName = [[NSString alloc] initWithFormat:@"fileName%d.jpg", count];
            [_uploadFile addFileFromMemory:strFileName fieldName:@"uploadFile" data:imgData];
            [_uploadFile addData:@"uploadFileName" value:strFileName];
        }
        [_uploadFile addData:@"itemBuilding.content" value:_footerView.contentTextView.text];
        [_uploadFile addData:@"itemBuilding.type" value:@"0"];
        [_uploadFile finishAddFile];
        [_uploadFile startUpload];
    }
    else
    {
        NSString *strRequestURL = @"";
        strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], addApplyURL];
        NSMutableString *strPost = [NSMutableString string];
        [strPost appendFormat:@"userId=%@", [AppDelegate getUserId]];
        for(NSDictionary *dic in _dataSourceArr)
        {
            [strPost appendFormat:@"&%@=%@", dic[@"field"], dic[@"value"]];
        }
        [strPost appendFormat:@"&itemBuilding.content=%@", _footerView.contentTextView.text];
        [strPost appendFormat:@"&itemBuilding.type=%@", @"0"];
        [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
            if(responseDic)
            {
                NSNumber *resValue = responseDic[@"isSuccess"];
                if([resValue intValue] == 1)
                {
                    [self showAlertView:@"发布成功" buttonTitle:ALERT_BTN_TITLE tag:@100 functionName:@"alertViewHandler:"];
                }
                else
                {
                    [self showAlertView:@"发布失败" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
                }
            }
        }];
    }
}

- (void)alertViewHandler:(id)obj
{
    NSNumber *value = (NSNumber *)obj;
    if([value integerValue] == 101)
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else
    {
        [self dismissViewControllerAnimated:YES completion:^{}];
    }
}



/**
 键盘显示与隐藏
 
 @param notification <#notification description#>
 */
- (void)keyboardWillShow:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    self.keyboardHeight = keyboardSize.height;
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.25f];
    UIView *tempView = [self.view findFirstResponder];
    if([tempView isKindOfClass:[UITextField class]])
    {
        if(_desRect.origin.y+_desRect.size.height > CGRectGetHeight(self.view.frame)-self.keyboardHeight)
        {
            self.distanceToMove = _desRect.origin.y+_desRect.size.height-(CGRectGetHeight(self.view.frame)-self.keyboardHeight);
            CGPoint pt = _tableView.contentOffset;
            pt.y += self.distanceToMove;
            [_tableView setContentOffset:pt animated:YES];
        }
    }
    else if([tempView isKindOfClass:[UITextView class]])
    {
        CGFloat textViewY = CGRectGetMinY(_footerView.frame) + 10;
        if(textViewY+tempView.frame.size.height-_tableView.contentOffset.y > CGRectGetHeight(self.view.frame)-self.keyboardHeight)
        {
            self.distanceToMove = textViewY+tempView.frame.size.height-_tableView.contentOffset.y - CGRectGetHeight(self.view.frame)+self.keyboardHeight;
            CGPoint pt = _tableView.contentOffset;
            pt.y += self.distanceToMove;
            [_tableView setContentOffset:pt animated:YES];
        }
    }
    
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.30f];
    CGPoint pt = _tableView.contentOffset;
    if(pt.y-self.distanceToMove < 0)
    {
        pt.y = 0;
    }
    else
    {
        pt.y -= self.distanceToMove;
    }
    [_tableView setContentOffset:pt animated:YES];
    [UIView commitAnimations];
}

#pragma mark - BIDPublishRentFooterViewDelegate
- (void)choosePhoto
{
    if(_footerView.addPhotoView.imgArr.count == _maxImgCount)
    {
        NSString *strHint = [[NSString alloc] initWithFormat:@"最多选择%ld张图片", _maxImgCount];
        [self showAlertView:strHint buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        return;
    }
    //
    ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initImagePicker];
    
    elcPicker.maximumImagesCount = _maxImgCount-_footerView.addPhotoView.imgArr.count; //Set the maximum number of images to select to 100
    elcPicker.returnsOriginalImage = YES; //Only return the fullScreenImage, not the fullResolutionImage
    elcPicker.returnsImage = YES; //Return UIimage if YES. If NO, only return asset location information
    elcPicker.onOrder = YES; //For multiple image selection, display and return order of selected images
    elcPicker.mediaTypes = @[(NSString *)kUTTypeImage]; //Supports image and movie types((NSString *)kUTTypeMovie)
    
    elcPicker.imagePickerDelegate = self;
    
    [self presentViewController:elcPicker animated:YES completion:nil];
}

- (void)resizeViewWithFrame:(CGRect)frame
{
    _footerView.frame = frame;
    _tableView.tableFooterView = _footerView;
}

- (void)showPhotoAtIndex:(NSInteger)index withImgArr:(NSArray *)arr
{
    BIDBrowserImageViewController *vc = [[BIDBrowserImageViewController alloc] initWithNibName:@"BIDBrowserImageViewController" bundle:nil];
    vc.index = index;
    vc.imgArr = [[NSArray alloc] initWithArray:arr];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    NSUInteger tag = textField.tag;
    NSDictionary *dic = _dataSourceArr[tag];
    if([dic[@"keyboardType"] isEqualToString:@"person"])
    {
        [textField resignFirstResponder];
        BIDMemberListViewController *vc = [[BIDMemberListViewController alloc] init];
        vc.delegate = self;
        vc.chooseType = TYPE_CHECK;
        [self.navigationController pushViewController:vc animated:YES];
    }
    else
    {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:textField.tag inSection:0];
        CGRect rectInTableView = [_tableView rectForRowAtIndexPath:indexPath];
        CGRect rect = [_tableView convertRect:rectInTableView toView:[_tableView superview]];
        _desRect = rect;
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSUInteger row = textField.tag;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:_dataSourceArr[row]];
    [dic setObject:textField.text forKey:@"value"];
    [dic setObject:textField.text forKey:@"content"];
    [_dataSourceArr replaceObjectAtIndex:row withObject:dic];
}

#pragma mark - BIDUpladFileDelegate
- (void)finishUploadWithResult:(id)obj
{
    if([obj isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *dic = (NSDictionary *)obj;
        NSNumber *value = dic[@"isSuccess"];
        if([value intValue] == 1)
        {
            [self showAlertView:@"发布成功" buttonTitle:ALERT_BTN_TITLE tag:@100 functionName:@"alertViewHandler:"];
        }
        else
        {
            NSString *strErrMsg = @"发布失败";
            [self showAlertView:strErrMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
    }
}

- (void)uploadFailedWithError:(NSError *)err
{
    [self showAlertView:[err localizedDescription] buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
}

#pragma mark - BIDMemberListViewControllerDelegate
- (void)getChoosedMember:(NSString *)ids andNames:(NSString *)names
{
    NSString *str = @"";
    NSArray *arr = [names componentsSeparatedByString:@","];
    if(arr && arr.count>5)
    {
        str = [[NSString alloc] initWithFormat:@"%@,%@等%ld人", arr[0], arr[1], arr.count];
    }
    else if(arr)
    {
        str = names;
    }
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:_dataSourceArr[0]];
    [dic setObject:ids forKey:@"value"];
    [dic setObject:str forKey:@"content"];
    [_dataSourceArr replaceObjectAtIndex:0 withObject:dic];
    [_tableView reloadData];
}

#pragma mark - BIDCustomDateViewDelegate
- (void)getDate:(NSString *)strDate
{
    UITextField *tf = (UITextField *)[self.view findFirstResponder];
    tf.text = strDate;
    NSUInteger row = tf.tag;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:_dataSourceArr[row]];
    [dic setObject:strDate forKey:@"value"];
    [dic setObject:strDate forKey:@"content"];
    [_dataSourceArr replaceObjectAtIndex:row withObject:dic];
}


#pragma mark - ELCImagePickerControllerDelegate Methods

- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:[info count]];
    for (NSDictionary *dict in info)
    {
        if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto)
        {
            if ([dict objectForKey:UIImagePickerControllerOriginalImage])
            {
                UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
                [images addObject:image];
                [_footerView.addPhotoView addPhoto:image];
            }
            else
            {
                NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
            }
        }
        else if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypeVideo)
        {
            if ([dict objectForKey:UIImagePickerControllerOriginalImage])
            {
                UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
                [images addObject:image];
            }
            else
            {
                NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
            }
        }
        else
        {
            NSLog(@"Uknown asset type");
        }
    }
}

- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *identifier = @"identifier";
    static NSString *switch_identifier = @"switch";
    NSUInteger row = indexPath.row;
    if(!_isRegister)
    {
        _isRegister = YES;
        UINib *nib1 = [UINib nibWithNibName:@"BIDCreateMeetingCell" bundle:nil];
        [tableView registerNib:nib1 forCellReuseIdentifier:identifier];
        //
        UINib *nib2 = [UINib nibWithNibName:@"BIDWithSwitchMeetingCell" bundle:nil];
        [tableView registerNib:nib2 forCellReuseIdentifier:switch_identifier];
    }
    NSDictionary *dic = _dataSourceArr[row];
    if(row == 6)
    {
        BIDWithSwitchMeetingCell *switchCell = [tableView dequeueReusableCellWithIdentifier:switch_identifier];
        switchCell.titleLabel.text = dic[@"title"];
        switchCell.switchCtrl.on = [dic[@"value"] isEqualToString:@"0"];
        [switchCell.switchCtrl addTarget:self action:@selector(switchValueChanged:) forControlEvents:UIControlEventValueChanged];
        cell = switchCell;
    }
    else
    {
        BIDCreateMeetingCell *meetingCell = [tableView dequeueReusableCellWithIdentifier:identifier];
        meetingCell.titleLabel.text = dic[@"title"];
        meetingCell.contentTF.text = ANY2NSSTRING(dic[@"content"]);
        meetingCell.contentTF.placeholder = dic[@"placeholder"];
        meetingCell.contentTF.tag = row;
        meetingCell.contentTF.delegate = self;
        if([dic[@"keyboardType"] isEqualToString:@"normal"])
        {
            meetingCell.contentTF.keyboardType = UIKeyboardTypeDefault;
            meetingCell.contentTF.inputAccessoryView = self.toolBar;
        }
        else if([dic[@"keyboardType"] isEqualToString:@"time"])
        {
            meetingCell.contentTF.inputView = _dateView;
            meetingCell.contentTF.inputAccessoryView = nil;
        }
        cell = meetingCell;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSUInteger row = indexPath.row;
    NSDictionary *dic = _dataSourceArr[row];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 6)
        return 54.f;
    return 79.f;
}

@end
